import { useReactive } from '.';
import { statePool } from '../compiler/state';
import { update } from '../render';
import { hasOwnProperty, isEqual, isObject } from '../sharde/utils'

const get = createGetter(),
  set = createSetter();

function createGetter() {
  return function get(target, key, receiver) {
    const res = Reflect.get(target, key, receiver)

    console.log("响应式获取： " + target[key]);

    if (isObject(res)) {
      // 深度代理
      return useReactive(res);
    }

    return res;
  }
}

function createSetter() {
  return function set(target, key, value, receiver) {
    const isKeyEcist = hasOwnProperty(target, key),
      oldValue = target[key],
      res = Reflect.set(target, key, value, receiver)

    if (!isKeyEcist) {
      console.log('响应式新增: ', key, value);
    } else if (!isEqual(value, oldValue)) {
      console.log("响应式修改: ", key, value)
      update(statePool, key, value);
      // View update
    }

    return res;
  }
}

const mutableHandle = {
  get,
  set
}

export { mutableHandle }